<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="small" @click="addPermissionBtn(0, 1)">添加权限</el-button>
      <el-table :data="permissionList" default-expand-all row-key="id">
        <el-table-column label="名称" prop="name" align="center" />
        <el-table-column label="标识" prop="code" align="center" />
        <el-table-column label="描述" prop="description" align="center" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button size="small" type="text" v-if="row.type === 1" @click="addPermissionBtn(row.id, 2)">添加</el-button>
            <el-button size="small" type="text" @click="editPermissionBtn(row)">编辑</el-button>
            <el-button size="small" type="text" @click="delPermissionBtn(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="showTitle" v-model="addPermissionDialog" width="600px" @close="btnCancel">
      <el-form ref="formRef" :model="permissionFormData" label-width="100px" :rules="PerMissionRules">
        <el-form-item label="名称" prop="name"> <el-input class="inputW" v-model="permissionFormData.name" /></el-form-item>
        <el-form-item label="权限标识" prop="code"> <el-input class="inputW" v-model="permissionFormData.code" /></el-form-item>
        <el-form-item label="权限描述" prop="description"> <el-input class="inputW" v-model="permissionFormData.description" /></el-form-item>
        <el-form-item label="权限状态" prop="enVisible"> <el-switch class="inputW" v-model="permissionFormData.enVisible" active-value="1" inactive-value="0" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" /></el-form-item>
      </el-form>
      <template #footer>
        <el-row justify="center">
          <el-button type="primary" @click="btnOk">确定</el-button>
          <el-button @click="btnCancel">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { getPermissionListApi, addPermission, updatePermission, delPermission, getPermissionDetail } from "@/api/permission";
import { onMounted, ref, computed } from "vue";
import { tranListToTreeData } from "@/utils";
import { log } from "console";
onMounted(() => {
  getPermissionList();
});
const permissionList = ref([]); // 权限列表树形结构数据
const addPermissionDialog = ref(false); // 添加权限弹窗显示隐藏状态
// 权限表单数据
const permissionFormData = ref({
  name: "",
  code: "",
  description: "",
  type: null, // 权限类型 1为页面路由权限点, 2为按钮权限点
  pid: null, // 父级权限ID 页面权限点pid值为'0', 按钮权限点值为所属页面权限点的id值
  enVisible: 0, // 是否启用 0为禁用,1为启用
});
const formRef = ref(); // 表单ref
const showTitle = computed(() => {
  return permissionFormData.value.id ? "编辑权限点" : "添加权限点";
});
// 自定义表单验证规则
// 权限点"名字"不能和子集们现有的权限点名字重复
const checkName = (rule, value, callback) => {
  const isNameExist = permissionList.value.some((item) => {
    if (item.name === value) return true;
    return item.children?.some((child) => child.name === value);
  });

  if (isNameExist) {
    callback(new Error("权限名称已存在"));
  } else {
    callback();
  }
};
//例如:权限标识不能和所有权限标识重复, 应该是唯一的标识
const checkCode = (rule, value, callback) => {
  const isCodeExist = permissionList.value.some((item) => {
    if (item.code === value) return true;
    return item.children?.some((child) => child.code === value);
  });

  if (isCodeExist) {
    callback(new Error("权限标识已存在"));
  } else {
    callback();
  }
};
// 新增权限点 注意1: 新增时, 权限点"名字"不能和子集们现有的权限点名字重复 注意2: 新增时, 权限标识不能和所有人重复, 应该是唯一的标识
const PerMissionRules = ref({
  name: [
    {
      required: true,
      message: "请输入权限名称",
      trigger: "blur",
    },

    { validator: checkName, trigger: "blur" },
  ],
  code: [
    {
      required: true,
      message: "请输入权限标识",
      trigger: "blur",
    },
    //请写一个校验 例如:权限标识不能和所有权限标识重复, 应该是唯一的标识
    { validator: checkCode, trigger: "blur" },
  ],
}); // 表单验证规则

// 获取权限列表数据 并转换为树形结构数据
const getPermissionList = async () => {
  const res = tranListToTreeData(await getPermissionListApi(), 0);

  permissionList.value = res;
  console.log(permissionList.value, "permissionList");
};
// 添加权限按钮点击事件处理函数
const addPermissionBtn = async (pid, type) => {
  // 赋值权限列表数据 并赋值pid和type值 注意: 1级页面权限点pid值为'0', 2级按钮权限点pid值为所属页面权限点的id值
  permissionFormData.value.pid = pid;
  permissionFormData.value.type = type;
  // console.log(permissionFormData.value);
  addPermissionDialog.value = true;
};
// 编辑权限按钮点击事件处理函数
const editPermissionBtn = async (row) => {
  const res = await getPermissionDetail(row.id); // 获取权限详情数据 并赋值给表单数据
  permissionFormData.value = res; // 赋值给表单数据
  addPermissionDialog.value = true; // 打开弹窗
};

// 添加权限按钮确定事件处理函数
const btnOk = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 判断是更新还是添加权限点 注意: 如果permissionFormData.value.id有值则为更新, 没有值为添加
      if (permissionFormData.value.id) {
        //编辑模式
        await updatePermission(permissionFormData.value);
        ElMessage.success("更新成功");
      } else {
        // 新增模式
        await addPermission(permissionFormData.value); // 调用添加权限接口
        ElMessage.success("添加成功");
      }
      btnCancel(); // 关闭弹窗并重置表单数据
      getPermissionList(); // 获取最新的权限列表数据并更新到页面上
    }
  });
};
const delPermissionBtn = async (row) => {
  ElMessageBox.confirm("是否删除该权限点?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await delPermission(row?.id);
        ElMessage.success("删除成功");
        await getPermissionList();
      } catch (error) {
        ElMessage.error(error?.message || "删除权限点失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const btnCancel = () => {
  //重置表单校验状态
  formRef.value.resetFields();
  // 重置表单数据
  permissionFormData.value = {
    name: "",
    code: "",
    description: "",
    type: null, // 权限类型 1为页面路由权限点, 2为按钮权限点
    pid: null, // 父级权限ID 页面权限点pid值为'0', 按钮权限点值为所属页面权限点的id值
    enVisible: 0, // 是否启用 0为禁用,1为启用
  };
  addPermissionDialog.value = false; // 关闭弹窗
};
</script>
<style lang="scss" scoped>
.inputW {
  width: 90%;
}
</style>
